package com.FindMyStuff.Activities;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;

import com.FindMyStuff.Model.DataAccessor;
import com.FindMyStuff.Model.DataBaseHelper;
import com.FindMyStuff.Model.InputChecker;
import com.FindMyStuff.Model.SessionManager;
import com.FindMyStuff.Model.User;
import com.FindMyStuff.Model.UserRole;

/**
 * An activity for the registration page
 *
 */

public class RegisterActivity extends Activity {
	/**
	 * Holds the SessionManager so garbage collection will not get rid of the session manager
	 */
	@SuppressWarnings("unused")
	private SessionManager sm;
	public final static String EXTRA_MESSAGE = "com.FindMyStuff.Activity.MESSAGE";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		sm = SessionManager.getInstance();
		setContentView(R.layout.activity_register);
		
		//Action Bar stuff
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setDisplayShowTitleEnabled(false);
		getActionBar().setIcon(getResources().getIdentifier("ic_logo", "drawable",  getPackageName()));
	}

	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			Intent toLogin = new Intent(this, LogInActivity.class);
			startActivity(toLogin);
			overridePendingTransition  (R.anim.left_slide_out, R.anim.left_slide_in);
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_register, menu);
		return true;
	}
	
	/**
	 * Attempts to register a User using the info in the text
	 * boxes
	 * @param view
	 */
	
	public void registerUser(View view) {
		
		EditText emailText = (EditText) findViewById(R.id.edit_email);
		EditText passwordText = (EditText) findViewById(R.id.edit_password);
		EditText confirmText = (EditText) findViewById(R.id.confirm_password);
		
		String email = emailText.getText().toString();
		String password = passwordText.getText().toString();
		String confirm = confirmText.getText().toString();
		String errors = InputChecker.checkPassword(password, confirm);
		if(!checkEmail(email)){
			errors = "Invalid email address.\n" +errors;
		}
		if(errors.equals("")){
			Intent intent = new Intent(this, LogInActivity.class);
			DataBaseHelper dbh = new DataBaseHelper(this);
			DataAccessor da = new DataAccessor(dbh);
			User user = da.createUser(email, password, UserRole.User);
			if(user.exist() == false)
			{
				errors = "Email address is already in use. \n";
			} else 
			{
				Dialog success =  createSuccessfulLogInDialog(intent);
				success.show();				
			}
		}
		if(errors.equals("") == false){
			Dialog errorDialog = createIncorrectLogInDialog(errors);
			errorDialog.show();
		}
		
	}
	
	/**
	 * Checks the email address that is passed in
	 * using regular expressions
	 * @param email The email to be checked
	 * @return true if valid, else false
	 */
	
	public boolean checkEmail(String email){
		return email.matches("[A-Za-z0-9]+[@][A-Za-z0-9]+(.com|.net|.edu)");
	}
	
	/**
	 * Creates a Dialog to display the errors found while
	 * checking the email and password
	 * 
	 * @param error The string containing all of the errors
	 * @return The Dialog object to be displayed
	 */
	
	public Dialog createIncorrectLogInDialog(String error) {
	    AlertDialog.Builder builder = new AlertDialog.Builder(this);

	    // Inflate and set the layout for the dialog
	    // Pass null as the parent view because its going in the dialog layout
	    builder.setMessage(error);
	    builder.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
	               @Override
	               public void onClick(DialogInterface dialog, int id) {
	                   
	               }
	           });
	    return builder.create();
	}
	
	/**
	 * Lets the user know that the log in was successful
	 * Dialog box changes current page to LogInActivity
	 * when the ok button is pressed
	 * 
	 * @param i An Intent object to transfer to LogInActivity
	 * @return The Dialog object to be used on successful login
	 */
	public Dialog createSuccessfulLogInDialog(final Intent i) {
	    AlertDialog.Builder builder = new AlertDialog.Builder(this);

	    // Inflate and set the layout for the dialog
	    // Pass null as the parent view because its going in the dialog layout
	    builder.setMessage(R.string.registration_success);
	    builder.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
	               @Override
	               //transfers to LogInActivity on button press
	               public void onClick(DialogInterface dialog, int id) {
	            	   startActivity(i);
	               }
	           });
	    return builder.create();
	}
}
